<template>
  <div class="location-recommendation-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="recommendation-form-card">
          <template #header>
            <div class="card-header">
              <h3>智能货位推荐</h3>
            </div>
          </template>
          
          <el-form :model="recommendationForm" label-width="100px" ref="recommendationFormRef">
            <el-form-item label="仓库选择" prop="warehouseId">
              <el-select v-model="recommendationForm.warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange">
                <el-option 
                  v-for="warehouse in warehouses" 
                  :key="warehouse.id" 
                  :label="warehouse.name" 
                  :value="warehouse.id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="推荐算法" prop="algorithm">
              <el-select v-model="recommendationForm.algorithm" placeholder="请选择推荐算法">
                <el-option label="最短路径优先" value="shortest_path" />
                <el-option label="周转率优先" value="turnover_rate" />
                <el-option label="相似物料聚类" value="material_clustering" />
                <el-option label="ABC分类存储" value="abc_classification" />
                <el-option label="智能混合算法" value="hybrid" />
              </el-select>
            </el-form-item>
            
            <el-divider content-position="left">物料信息</el-divider>
            
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="recommendationForm.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
            
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="recommendationForm.materialName" placeholder="请输入物料名称" />
            </el-form-item>
            
            <el-form-item label="物料类型" prop="materialType">
              <el-select v-model="recommendationForm.materialType" placeholder="请选择物料类型">
                <el-option label="原材料" value="raw" />
                <el-option label="半成品" value="semi" />
                <el-option label="成品" value="finished" />
                <el-option label="包装材料" value="packaging" />
                <el-option label="辅料" value="auxiliary" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="物料规格" prop="specification">
              <el-input v-model="recommendationForm.specification" placeholder="请输入物料规格" />
            </el-form-item>
            
            <el-form-item label="存储条件" prop="storageCondition">
              <el-select v-model="recommendationForm.storageCondition" placeholder="请选择存储条件">
                <el-option label="常温" value="normal" />
                <el-option label="恒温" value="constant" />
                <el-option label="冷藏" value="refrigerated" />
                <el-option label="冷冻" value="frozen" />
                <el-option label="防潮" value="moisture_proof" />
                <el-option label="防晒" value="sun_proof" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="危险等级" prop="dangerLevel">
              <el-rate v-model="recommendationForm.dangerLevel" :max="3" show-score />
            </el-form-item>
            
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="recommendationForm.quantity" :min="1" :step="1" />
            </el-form-item>
            
            <el-form-item label="周转频率" prop="turnoverFrequency">
              <el-select v-model="recommendationForm.turnoverFrequency" placeholder="请选择周转频率">
                <el-option label="高频" value="high" />
                <el-option label="中频" value="medium" />
                <el-option label="低频" value="low" />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="generateRecommendation" :loading="loading">生成推荐</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="recommendation-result-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <h3>推荐结果</h3>
              <div v-if="recommendations.length > 0">
                <el-button type="success" @click="applyRecommendation">应用推荐</el-button>
                <el-button type="primary" @click="exportRecommendation">导出结果</el-button>
              </div>
            </div>
          </template>
          
          <div v-if="recommendations.length > 0" class="recommendation-results">
            <el-alert
              title="智能推荐完成"
              type="success"
              description="系统已根据您提供的信息生成最优货位推荐，请查看以下推荐结果。"
              show-icon
              :closable="false"
              style="margin-bottom: 20px"
            />
            
            <el-table :data="recommendations" border style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="locationCode" label="货位编码" width="120" />
              <el-table-column prop="area" label="库区" width="100" />
              <el-table-column prop="rack" label="货架号" width="100" />
              <el-table-column prop="level" label="层级" width="80" />
              <el-table-column prop="position" label="位置" width="80" />
              <el-table-column prop="score" label="匹配度" width="100">
                <template #default="scope">
                  <el-progress :percentage="scope.row.score" :color="getScoreColor(scope.row.score)" />
                </template>
              </el-table-column>
              <el-table-column prop="distanceToEntrance" label="距入口距离" width="120">
                <template #default="scope">
                  {{ scope.row.distanceToEntrance }} 米
                </template>
              </el-table-column>
              <el-table-column prop="capacity" label="可用容量" width="100">
                <template #default="scope">
                  {{ scope.row.capacity }}%
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="推荐理由" />
            </el-table>
            
            <div class="recommendation-visualization">
              <h4>货位可视化</h4>
              <div class="warehouse-map">
                <div class="warehouse-entrance">入口</div>
                <div 
                  v-for="(rec, index) in recommendations" 
                  :key="index"
                  class="location-marker"
                  :class="{ 'top-recommendation': index === 0 }"
                  :style="getLocationStyle(rec, index)"
                >
                  {{ index + 1 }}
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="no-recommendation">
            <el-empty description="请填写物料信息并生成推荐" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 应用推荐确认对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="确认应用推荐"
      width="40%"
    >
      <div class="confirm-content">
        <p>您确定要将物料 <strong>{{ recommendationForm.materialName }}</strong> 分配到推荐的货位吗？</p>
        <p>首选货位: <strong>{{ recommendations[0]?.locationCode || '' }}</strong></p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmApply">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'IntelligentLocation',
  setup() {
    // 状态
    const loading = ref(false)
    const recommendations = ref([])
    const confirmDialogVisible = ref(false)
    const recommendationFormRef = ref(null)
    
    // 仓库数据
    const warehouses = ref([
      { id: 'WH001', name: '中央仓库' },
      { id: 'WH002', name: '北区配送中心' },
      { id: 'WH003', name: '南方仓储中心' },
      { id: 'WH004', name: '西部物流中心' }
    ])
    
    // 推荐表单
    const recommendationForm = reactive({
      warehouseId: '',
      algorithm: 'hybrid',
      materialCode: '',
      materialName: '',
      materialType: '',
      specification: '',
      storageCondition: 'normal',
      dangerLevel: 0,
      quantity: 1,
      turnoverFrequency: 'medium'
    })
    
    // 处理仓库变更
    const handleWarehouseChange = (warehouseId) => {
      // 清空推荐结果
      recommendations.value = []
    }
    
    // 生成推荐
    const generateRecommendation = () => {
      // 表单验证
      if (!recommendationForm.warehouseId) {
        ElMessage.warning('请选择仓库')
        return
      }
      
      if (!recommendationForm.materialCode || !recommendationForm.materialName) {
        ElMessage.warning('请输入物料编码和名称')
        return
      }
      
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        // 生成模拟推荐结果
        recommendations.value = [
          {
            locationCode: 'A-03-02-05',
            area: 'A区',
            rack: '03',
            level: '02',
            position: '05',
            score: 98,
            distanceToEntrance: 15,
            capacity: 100,
            reason: '该货位临近同类物料，且距离入口较近，适合中频周转物料'
          },
          {
            locationCode: 'A-03-03-02',
            area: 'A区',
            rack: '03',
            level: '03',
            position: '02',
            score: 92,
            distanceToEntrance: 16,
            capacity: 100,
            reason: '该货位与首选货位在同一货架，适合批量存储'
          },
          {
            locationCode: 'A-04-02-01',
            area: 'A区',
            rack: '04',
            level: '02',
            position: '01',
            score: 85,
            distanceToEntrance: 18,
            capacity: 100,
            reason: '该货位存储条件适合该物料，且有足够空间'
          },
          {
            locationCode: 'B-01-01-03',
            area: 'B区',
            rack: '01',
            level: '01',
            position: '03',
            score: 78,
            distanceToEntrance: 25,
            capacity: 100,
            reason: 'B区有相似物料，适合集中管理'
          },
          {
            locationCode: 'B-02-02-04',
            area: 'B区',
            rack: '02',
            level: '02',
            position: '04',
            score: 70,
            distanceToEntrance: 30,
            capacity: 100,
            reason: '备选货位，满足基本存储条件'
          }
        ]
        
        loading.value = false
        ElMessage.success('已生成推荐货位')
      }, 1500)
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(recommendationForm, {
        warehouseId: '',
        algorithm: 'hybrid',
        materialCode: '',
        materialName: '',
        materialType: '',
        specification: '',
        storageCondition: 'normal',
        dangerLevel: 0,
        quantity: 1,
        turnoverFrequency: 'medium'
      })
      recommendations.value = []
    }
    
    // 应用推荐
    const applyRecommendation = () => {
      if (recommendations.value.length === 0) return
      confirmDialogVisible.value = true
    }
    
    // 确认应用
    const confirmApply = () => {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(`已将物料 ${recommendationForm.materialName} 分配到货位 ${recommendations.value[0].locationCode}`)
        confirmDialogVisible.value = false
      }, 500)
    }
    
    // 导出推荐结果
    const exportRecommendation = () => {
      ElMessage.success('推荐结果已导出')
    }
    
    // 获取匹配度颜色
    const getScoreColor = (score) => {
      if (score >= 90) return '#67C23A'
      if (score >= 80) return '#409EFF'
      if (score >= 70) return '#E6A23C'
      return '#F56C6C'
    }
    
    // 获取货位标记样式
    const getLocationStyle = (location, index) => {
      // 简单模拟货位在地图上的位置
      const baseLeft = 10 + (location.rack * 15)
      const baseTop = 10 + (location.level * 15)
      
      return {
        left: `${baseLeft}%`,
        top: `${baseTop}%`
      }
    }
    
    return {
      loading,
      warehouses,
      recommendationForm,
      recommendationFormRef,
      recommendations,
      confirmDialogVisible,
      
      handleWarehouseChange,
      generateRecommendation,
      resetForm,
      applyRecommendation,
      confirmApply,
      exportRecommendation,
      getScoreColor,
      getLocationStyle
    }
  }
}
</script>

<style>
.location-recommendation-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendation-form-card {
  height: calc(100vh - 140px);
  overflow-y: auto;
}

.recommendation-result-card {
  height: calc(100vh - 140px);
  overflow-y: auto;
}

.recommendation-results {
  padding: 10px;
}

.recommendation-visualization {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.warehouse-map {
  position: relative;
  height: 300px;
  background-color: #eee;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-top: 10px;
}

.warehouse-entrance {
  position: absolute;
  left: 0;
  top: 0;
  background-color: #409EFF;
  color: white;
  padding: 5px 10px;
  border-radius: 0 0 4px 0;
}

.location-marker {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #909399;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.location-marker.top-recommendation {
  background-color: #67C23A;
  width: 40px;
  height: 40px;
  z-index: 10;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}

.no-recommendation {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-content {
  padding: 20px;
  text-align: center;
}

/* 确保下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}
</style> 